package cn.tude.alipay.pay.controller;


import cn.tude.alipay.pay.pojo.entity.Order;
import com.alipay.easysdk.factory.Factory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.tude.alipay.base.config.AlipayConfig;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("alipay")
@Transactional(rollbackFor = Exception.class)
public class PayController {

    @Resource
    AlipayConfig aliPayConfig;


    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT = "JSON";
    private static final String CHARSET = "utf-8";
    private static final String SIGN_TYPE = "RSA2";

    @GetMapping("/pay") // &subject=xxx&traceNo=xxx&totalAmount=xxx
    public void pay(Order order, HttpServletResponse httpResponse) throws Exception {
        System.out.println(111);
        // 创建支付宝客户端对象，传入网关地址、应用 ID、应用私钥、格式、字符集、支付宝公钥和签名类型
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);
        // 创建支付宝网页支付请求对象
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        // 设置支付成功后的异步通知地址
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        // 设置业务内容，包括商户订单号、总金额、商品名称和产品代码
        request.setBizContent("{\"out_trade_no\":\"" + order.getOrderId() + "\","
                + "\"total_amount\":\"" + order.getPrice() + "\","
                + "\"subject\":\"" + order.getProduct() + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //支付完成之后跳转会原来的页面
        request.setReturnUrl("http://localhost:9091/");
        String form = "";
        try {
            // 调用支付宝客户端的 pageExecute 方法生成支付表单，若出现异常则打印堆栈信息
            form = alipayClient.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        // 设置响应的内容类型为 HTML 格式，并指定字符集
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        // 将生成的支付表单 HTML 内容输出到页面
        httpResponse.getWriter().write(form);
        // 刷新输出流
        httpResponse.getWriter().flush();
        // 关闭输出流
        httpResponse.getWriter().close();
    }
    @PostMapping("/notify")
    public String payNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 判断支付宝通知中的交易状态是否为 TRADE_SUCCESS
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");

            // 创建一个存储请求参数的 Map
            Map<String, String> params = new HashMap<>();
            // 获取所有请求参数并放入 Map
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
                // System.out.println(name + " = " + request.getParameter(name));
            }

            // 从参数中获取交易号、支付时间、支付宝交易号等信息
            String tradeNo = params.get("out_trade_no");
            String gmtPayment = params.get("gmt_payment");
            String alipayTradeNo = params.get("trade_no");

            // 调用验签方法进行支付宝通知的验签
            if (Factory.Payment.Common().verifyNotify(params)) {
                // 验签通过后的处理逻辑
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一 id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));
//                // 更新订单状态为已支付，并设置订单 ID 和状态
//                Orders order = new Orders();
//                order.setId(Long.valueOf(tradeNo));
//                order.setStatus(2);
////            order.setCheckoutTime(params.get("gmt_payment"));
//                shopOrderMapper.updateById(order);
            }
        }
        // 返回 success，表示处理成功
        return "success";
    }
}
//    @GetMapping("/pay") // &subject=xxx&traceNo=xxx&totalAmount=xxx
//    public void pay(Alipay aliPay, HttpServletResponse httpResponse) throws Exception {
//        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
//                aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);
//        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
//        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
//        request.setBizContent("{\"out_trade_no\":\"" + aliPay.getTraceNo() + "\","
//                + "\"total_amount\":\"" + aliPay.getTotalAmount() + "\","
//                + "\"subject\":\"" + aliPay.getSubject() + "\","
//                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
//        String form = "";
//        try {
//            // 调用SDK生成表单
//            form = alipayClient.pageExecute(request).getBody();
//        } catch (AlipayApiException e) {
//            e.printStackTrace();
//        }
//        httpResponse.setContentType("text/html;charset=" + CHARSET);
//        // 直接将完整的表单html输出到页面
//        httpResponse.getWriter().write(form);
//        httpResponse.getWriter().flush();
//        httpResponse.getWriter().close();
//    }
//    @PostMapping("/notify")  // 注意这里必须是POST接口
//    public String payNotify(HttpServletRequest request) throws Exception {
//        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
//            System.out.println("=========支付宝异步回调========");
//
//            Map<String, String> params = new HashMap<>();
//            Map<String, String[]> requestParams = request.getParameterMap();
//            for (String name : requestParams.keySet()) {
//                params.put(name, request.getParameter(name));
//                // System.out.println(name + " = " + request.getParameter(name));
//            }
//
//            String tradeNo = params.get("out_trade_no");
//            String gmtPayment = params.get("gmt_payment");
//            String alipayTradeNo = params.get("trade_no");
//            // 支付宝验签
//            if (Factory.Payment.Common().verifyNotify(params)) {
//                // 验签通过
//                System.out.println("交易名称: " + params.get("subject"));
//                System.out.println("交易状态: " + params.get("trade_status"));
//                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
//                System.out.println("商户订单号: " + params.get("out_trade_no"));
//                System.out.println("交易金额: " + params.get("total_amount"));
//                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
//                System.out.println("买家付款时间: " + params.get("gmt_payment"));
//                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));
//                // 更新订单未已支付
//                Orders order = new Orders();
//                order.setId(Long.valueOf(tradeNo));
//                order.setStatus(2);
////                order.setCheckoutTime(params.get("gmt_payment"));
//                shopOrderMapper.updateById(order);
//            }
//        }
//        return "success";
//    }
//}


